package yby

import (
	"errors"
	"fmt"
	"gitee.com/hongzhaomin/hzm-common-go/easycmd"
	"github.com/xuri/excelize/v2"
	_ "image/gif"
	_ "image/jpeg"
	_ "image/png"
)

const (
	sheetName = "Sheet1"
	no        = "款号"
	mainImg   = "主图"
)

var _ easycmd.Handler = (*FindPic)(nil)

type FindPic struct {
	SrcExcel string `json:"srcExcel,omitempty" argName:"s" usage:"需要查找图片的Excel文件"`
	DstExcel string `json:"dstExcel,omitempty" argName:"d" usage:"需要补充图片的Excel文件"`
}

func (my *FindPic) DoHandle(_ *easycmd.Command) {
	if my.SrcExcel == "" {
		fmt.Println("请输入需要查找图片的Excel文件, 例如: -s=a.xlsx")
		return
	}
	if my.DstExcel == "" {
		fmt.Println("请输入需要补充图片的Excel文件, 例如: -d=b.xlsx")
		return
	}
	my.doFindPic()
}

func (my *FindPic) doFindPic() {
	// 打开源文件
	sf, err := excelize.OpenFile(my.SrcExcel)
	if err != nil {
		fmt.Println(fmt.Sprintf("读取excel文件[%s]失败: %v", my.SrcExcel, err))
		return
	}
	defer sf.Close()

	sRowsList, _ := sf.GetRows(sheetName)
	sTitle2ColNumMap, err := my.getTitle2ColNumMap(sRowsList[0])
	if err != nil {
		fmt.Println(fmt.Sprintf("excel文件[%s]缺少表头信息: %v", my.SrcExcel, err))
		return
	}
	sNo2RowNumMap := make(map[string]int)
	sColsList, _ := sf.GetCols(sheetName)
	for sRowIndex, sNoVal := range sColsList[sTitle2ColNumMap[no]-1] {
		if sNoVal == no {
			continue
		}
		sNo2RowNumMap[sNoVal] = sRowIndex + 1
	}

	// 打开目标文件
	df, err := excelize.OpenFile(my.DstExcel)
	if err != nil {
		fmt.Println(fmt.Sprintf("读取excel文件[%s]失败: %v", my.DstExcel, err))
		return
	}
	defer df.Close()

	dRowsList, _ := df.GetRows(sheetName)
	dTitle2ColNumMap, err := my.getTitle2ColNumMap(dRowsList[0])
	if err != nil {
		fmt.Println(fmt.Sprintf("excel文件[%s]缺少表头信息: %v", my.DstExcel, err))
		return
	}
	// 设置列宽
	colName, _ := excelize.ColumnNumberToName(dTitle2ColNumMap[mainImg])
	_ = df.SetColWidth(sheetName, colName, colName, 9) // A列宽9字符

	dColsList, _ := df.GetCols(sheetName)
	for dRowIndex, dNoVal := range dColsList[dTitle2ColNumMap[no]-1] {
		if dNoVal == no {
			continue
		}
		dRowNum := dRowIndex + 1
		dMainImgCell, _ := excelize.CoordinatesToCellName(dTitle2ColNumMap[mainImg], dRowNum)

		sRowNum, ok := sNo2RowNumMap[dNoVal]
		if !ok {
			continue
		}
		sMainImgCell, _ := excelize.CoordinatesToCellName(sTitle2ColNumMap[mainImg], sRowNum)
		// 读取源文件图片
		pics, err2 := sf.GetPictures(sheetName, sMainImgCell)
		if err2 != nil {
			fmt.Println(fmt.Sprintf("读取图片文件失败, excel: [%s], sheet: [%s], cell: [%s]: %v",
				my.SrcExcel, sheetName, sMainImgCell, err2))
			continue
		}
		// 设置行高
		_ = df.SetRowHeight(sheetName, dRowNum, 50) // 第2行高50磅

		for _, pic := range pics {
			err = df.AddPictureFromBytes(sheetName, dMainImgCell, &excelize.Picture{
				Extension: pic.Extension,
				File:      pic.File,
				Format: &excelize.GraphicOptions{
					OffsetX: 3,
					OffsetY: 4,
					ScaleX:  0.95,
					ScaleY:  0.90,
				},
			})
			if err != nil {
				fmt.Println(fmt.Sprintf("添加图片失败, cell: [%s]: %v", dMainImgCell, err))
				continue
			}
		}
	}

	if err = df.Save(); err != nil {
		fmt.Println(fmt.Sprintf("Excel文件[%s]保存失败: %v", my.DstExcel, err))
		return
	}
	fmt.Println(">>> 图片查找成功")
}

func (my *FindPic) getTitle2ColNumMap(titles []string) (map[string]int, error) {
	title2ColNumMap := map[string]int{
		no:      0,
		mainImg: 0,
	}
	for i, title := range titles {
		if _, ok := title2ColNumMap[title]; ok {
			title2ColNumMap[title] = i + 1
		}
	}

	if title2ColNumMap[no] == 0 {
		return nil, errors.New(fmt.Sprintf("找不到表头[%s]", no))
	}
	if title2ColNumMap[mainImg] == 0 {
		return nil, errors.New(fmt.Sprintf("找不到表头[%s]", mainImg))
	}
	return title2ColNumMap, nil
}
